<template>
    <div class="_container">
        <a-form class="_form" layout="inline" :form="form">
          <a-form-item>
                <a-select v-model="form.county" placeholder="县市区" allowClear style="width: 120px" @change="changeHanale">
                    <a-select-option :defaultValue="item.code[0]" v-for="item in countyArr" :key="item.code">{{item.name}}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item>
                <a-month-picker
                        style="width:150px"
                        allowClear
                        v-model="form.selectTime"
                        format="YYYY-MM"
                        :open="yearShow"
                        placeholder="请选择日期"
                        @change="changeHanale"
                        @openChange="onOpenChange"
                        @panelChange="onPanelChange">
                </a-month-picker>
            </a-form-item>
        </a-form>
        <div class="_body">
            <div class="item">
                <div class="_tit">全市趋势图</div>
                <div class="_chart">
                    <e-chart :option="effectOption"></e-chart>
                </div>
            </div>
            <div class="item">
                <div class="_tit">区县成效图</div>
                <div class="tabs">
                    <a-button v-for="item in tabsArr" :key="item.value" :type="curTab == item.value?'primary':''" @click="tabsClick(item.value)">
                        {{item.label}}
                    </a-button>
                </div>
                <div class="_chart">
                    <e-chart :option="countyEffectOption"></e-chart>
                </div>
            </div>
            <div class="item">
                <div class="_tit">
                    <a-button class="_back" v-if="columnName != '区划'" size="small" shape="circle" icon="left" @click="getTableData('330300')" />
                    工作晾晒台
                </div>
                <div class="_table">
                    <a-table :columns="columns" :data-source="tableData" :pagination="false" :scroll="{x: false, y: '410px'}">
                        <a slot="name" slot-scope="text, row" @click="rowClick(row)">{{ text }}</a>
                        <span slot="customTitle">{{columnName}}</span>
                        <template slot="ratio" slot-scope="text, row">
                            <font :color="row.result==1?'#FF0000':row.result==2?'#67C23A':'#409EFF'">
                                {{row.ratio}} {{row.result==1?'↑':row.result==2?'↓':'→'}}
                            </font>
                        </template>
                    </a-table>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {
  getCheckTaskPatrol, getHandleTaskDry, getCheckTaskPatrolTime
} from "@/services/system/whdngxlApi";
    import eChart from './echart'
import moment from "moment";
    export default {
        name: 'tasksPatrol',
        components: { eChart },
        data() {
            return {
                yearShow: false,
              d0706List:[
                {name: '常态任务', code: '1'},
                {name: '专项任务', code: '2'},
              ],
                countyArr: [
                  {name: '温州市', code: '330300000000'},
                    {name: '龙湾', code: '330303'},
                    {name: '瓯海', code: '330304'},
                    {name: '鹿城', code: '330302'},
                    {name: '苍南', code: '330327'},
                    {name: '洞头', code: '330305'},
                    {name: '瑞安', code: '330381'},
                    {name: '乐清', code: '330382'},
                    {name: '龙港', code: '330383'},
                    {name: '永嘉', code: '330324'},
                    {name: '平阳', code: '330326'},
                    {name: '文成', code: '330328'},
                    {name: '泰顺', code: '330329'}
                ],
                monthArr: [
                    { label: '一月', value: '01' },
                    { label: '二月', value: '02' },
                    { label: '三月', value: '03' },
                    { label: '四月', value: '04' },
                    { label: '五月', value: '05' },
                    { label: '六月', value: '06' },
                    { label: '七月', value: '07' },
                    { label: '八月', value: '08' },
                    { label: '九月', value: '09' },
                    { label: '十月', value: '10' },
                    { label: '十一月', value: '11' },
                    { label: '十二月', value: '12' },
                ],
                form: {
                    county: '330300000000',
                    year: new Date().getFullYear() + '',
                    month: new Date().getMonth() +1+ '',
                  selectTime:moment(new Date()),
                  type: '1'
                },
                effectOption: {},
                curTab: '',
                tabsArr: [
                    { label: '完成率(%)', value: 'rate' },
                    { label: '完成效率(小时)', value: 'efficiency' },
                ],
                countyEffectOption: {},
              initialTableData:[],
                // initialTableData: [
                //     {name: '鹿城区', code: '330302', parentCode: '330300', score: '95', ratio: '2名', result: '1'},
                //     {name: '龙湾区', code: '330303', parentCode: '330300', score: '90', ratio: '1名', result: '2'},
                //     {name: '瓯海区', code: '330304', parentCode: '330300', score: '85', ratio: '1名', result: '1'},
                //     {name: '洞头区', code: '330305', parentCode: '330300', score: '80', ratio: '2名', result: '2'},
                //     {name: '瑞安市', code: '330381', parentCode: '330300', score: '78', ratio: '持平', result: '3'},
                //     {name: '乐清市', code: '330382', parentCode: '330300', score: '75', ratio: '2名', result: '2'},
                //     {name: '龙港市', code: '330383', parentCode: '330300', score: '73', ratio: '1名', result: '1'},
                //     {name: '永嘉县', code: '330324', parentCode: '330300', score: '71', ratio: '持平', result: '3'},
                //     {name: '平阳县', code: '330326', parentCode: '330300', score: '68', ratio: '2名', result: '2'},
                //     {name: '苍南县', code: '330327', parentCode: '330300', score: '66', ratio: '2名', result: '2'},
                //     {name: '文成县', code: '330328', parentCode: '330300', score: '65', ratio: '1名', result: '1'},
                //     {name: '泰顺县', code: '330329', parentCode: '330300', score: '63', ratio: '2名', result: '1'},
                //     {name: '五马街道', code: '', parentCode: '330302', score: '63', ratio: '2名', result: '1'},
                //     {name: '大南街道', code: '', parentCode: '330302', score: '90', ratio: '1名', result: '2'},
                //     {name: '松台街道', code: '', parentCode: '330302', score: '85', ratio: '1名', result: '1'},
                //     {name: '广化街道', code: '', parentCode: '330302', score: '80', ratio: '2名', result: '2'},
                //     {name: '滨江街道', code: '', parentCode: '330302', score: '78', ratio: '持平', result: '3'},
                //     {name: '蒲鞋市街道', code: '', parentCode: '330302', score: '75', ratio: '2名', result: '2'},
                //     {name: '南汇街道', code: '', parentCode: '330302', score: '73', ratio: '1名', result: '1'},
                //     {name: '南郊街道', code: '', parentCode: '330302', score: '71', ratio: '持平', result: '3'},
                //     {name: '双屿街道', code: '', parentCode: '330302', score: '68', ratio: '2名', result: '2'},
                //     {name: '丰门街道', code: '', parentCode: '330302', score: '66', ratio: '2名', result: '2'},
                //     {name: '七都街道', code: '', parentCode: '330302', score: '65', ratio: '1名', result: '1'},
                //     {name: '仰义街道', code: '', parentCode: '330302', score: '63', ratio: '2名', result: '1'},
                //     {name: '藤桥镇', code: '', parentCode: '330302', score: '63', ratio: '2名', result: '1'},
                //     {name: '山福镇', code: '', parentCode: '330302', score: '90', ratio: '1名', result: '2'},
                //     {name: '永中街道', code: '', parentCode: '330303', score: '63', ratio: '2名', result: '1'},
                //     {name: '蒲州街道', code: '', parentCode: '330303', score: '90', ratio: '1名', result: '2'},
                //     {name: '海滨街道', code: '', parentCode: '330303', score: '85', ratio: '1名', result: '1'},
                //     {name: '永兴街道', code: '', parentCode: '330303', score: '80', ratio: '2名', result: '2'},
                //     {name: '状元街道', code: '', parentCode: '330303', score: '78', ratio: '持平', result: '3'},
                //     {name: '瑶溪街道', code: '', parentCode: '330303', score: '75', ratio: '2名', result: '2'},
                //
                //     {name: '景山街道', code: '', parentCode: '330304', score: '75', ratio: '2名', result: '2'},
                //     {name: '梧田街道', code: '', parentCode: '330304', score: '90', ratio: '1名', result: '2'},
                //     {name: '茶山街道', code: '', parentCode: '330304', score: '85', ratio: '1名', result: '1'},
                //     {name: '南白象街道', code: '', parentCode: '330304', score: '80', ratio: '2名', result: '2'},
                //     {name: '新桥街道', code: '', parentCode: '330304', score: '78', ratio: '持平', result: '3'},
                //     {name: '娄桥街道', code: '', parentCode: '330304', score: '75', ratio: '2名', result: '2'},
                //     {name: '三垟街道', code: '', parentCode: '330304', score: '73', ratio: '1名', result: '1'},
                //     {name: '瞿溪街道', code: '', parentCode: '330304', score: '71', ratio: '持平', result: '3'},
                //     {name: '潘桥街道', code: '', parentCode: '330304', score: '68', ratio: '2名', result: '2'},
                //     {name: '郭溪街道', code: '', parentCode: '330304', score: '66', ratio: '2名', result: '2'},
                //     {name: '丽岙街道', code: '', parentCode: '330304', score: '65', ratio: '1名', result: '1'},
                //     {name: '仙岩街道', code: '', parentCode: '330304', score: '63', ratio: '2名', result: '1'},
                //     {name: '泽雅镇', code: '', parentCode: '330304', score: '63', ratio: '2名', result: '1'},
                // ],
                columnName: '区划',
                tableData: [],
                columns: [
                    {
                      dataIndex: 'tj0605',
                      key: 'tj0605',
                        title: '排名',
                        align: 'center',
                        customRender: (text, record, index) => `${index + 1}`
                    },
                    {
                      title: '区划名称',
                        dataIndex: 'orgName',
                        key: 'orgName',
                        slots: { title: 'customTitle' },
                        scopedSlots: { customRender: 'orgName' },
                        align: 'center'
                    },
                    {
                        title: '综合分数',
                        dataIndex: 'tj0604',
                        key: 'tj0604',
                        align: 'center'
                    },
                    // {
                    //     title: '环比',
                    //     dataIndex: 'tj0605',
                    //     key: 'tj0605',
                    //     scopedSlots: { customRender: 'tj0605' },
                    //     align: 'center'
                    // }
                ],
              astasksPlan:[],
              hours:[],
              tj06List:[],
            }
        },
        mounted() {
            this.$nextTick(()=>{
              this.initData();
              console.log("####",this.$store.state.user)
            })
          //this.getTableData('330300')
        },
        methods: {
          changeHanale(){
            this.initData()
          },
          initData() {
            this.tj06List = [],
            this.tableData = [],
                this.hours = [],
                this.astasksPlan = []
            this.$nextTick(() => {
              this.getTotal();
            })
          },
          getTotal(){
            const params = {};
            params.type=this.form.type, //巡查
            params.orgId=this.form.county,
            params.dateType='1',//时间类型 0周 1月 2季
            params.selectTime=this.form.selectTime
            this.$http.post(getHandleTaskDry,params).then(res => {
                if (res.result.tj06List){
                  this.tj06List = res.result.tj06List
                }
                if (res.result.tj05){
                  this.getEffectOption([
                    {name: '已完成', value: res.result.tj05.tj0502?res.result.tj05.tj0502:0},
                    {name: '未完成', value: res.result.tj05.tj0503?res.result.tj05.tj0503:0}
                  ])
                }else{
                  this.getEffectOption([
                    {name: '已完成', value: 0},
                    {name: '未完成', value: 0}
                  ])
                }

              this.tabsClick('rate')
            })
          },
            onOpenChange(status) {
                this.yearShow =  status
            },
            onPanelChange(value, mode) {
                this.form.selectTime = value.format('yyyy-MM')
                this.yearShow = false
            },
            getEffectOption(data){
                let total = 0, done = 0
                for (let i = 0, l = data.length; i < l; i++) {
                    total += Number(data[i].value)
                    if(data[i].name === '已完成'){
                      done = Number(data[i].value)
                    }
                }
                this.effectOption = {
                    graphic: [
                        {
                            type: 'text',
                            left: 'center',
                            top: '35%',
                            style: {
                                text: `${total === 0 ? '0' : ((done / total) * 100).toFixed(0)} %`,
                                textAlign: 'center',
                                fill: '#333', //文字的颜色
                                width: 30,
                                height: 30,
                                fontSize: 28,
                                fontWeight: 'bold'
                            }
                        },
                        {
                            type: 'text',
                            left: 'center',
                            top: '44%',
                            style: {
                                text: `巡查率`,
                                textAlign: 'center',
                                fill: '#333', //文字的颜色
                                width: 30,
                                height: 30,
                                fontSize: 16,
                            }
                        }
                    ],
                    grid: {
                        top: '10%',
                    },
                    legend: {
                        orient: 'vertical', // 图例列表的布局朝向
                        bottom: 50,
                        itemGap: 10, // 图例每项之间的间隔。
                        icon: 'circle',
                        itemHeight: 8,
                        formatter: function (name) {
                            let target
                            for (let i = 0, l = data.length; i < l; i++) {
                                if (data[i].name == name) {
                                    target = Number(data[i].value)
                                }
                            }
                            let arr = [
                                '{a|' + name + '}',
                                '{b|' + target + ' 处}'
                            ]
                            return arr.join('  ')
                        },
                        textStyle: {
                            rich: {
                                a: {
                                    fontSize: 14,
                                    padding: [0, 12, 0, 6]
                                },
                                b: {
                                    fontSize: 14,
                                    padding: [0, 16, 0, 0]
                                }
                            }
                        }
                    },
                    series: [
                        {
                            selectedMode: 'multiple',
                            // top: '-3%',
                            type: 'pie',
                            radius: ['48%', '65%'], //圆环内外径
                            center: ['50%', '40%'],
                            avoidLabelOverlap: true,
                            label: {
                                show: false,
                            },
                            labelLine: {
                                show: false
                            },
                            animationDuration: 2800,
                            animationEasing: 'cubicInOut',
                            data: data
                        }
                    ]
                }
            },
          tabsClick(e) {
            this.curTab = e;
            // 定义所有需要显示的行政区划
            const allDistricts = ['鹿城','龙湾','瓯海','洞头','瑞安','乐清','龙港','永嘉','平阳','苍南','文成','泰顺'];
            let xAxisName = [];
            let xAxisData = [];
            let unit = '';

            // 根据选中的标签设置单位
            if (e === 'rate') {
              unit = '%';
            } else {
              unit = 'h';
            }

            // 处理表格数据 - 确保所有行政区划都有记录
            this.tableData = allDistricts.map(district => {
              // 查找对应的数据
              const foundItem = this.tj06List.find(item =>
                  item.orgName && item.orgName.substring(0, 2) === district
              );
              // 有数据则使用实际值，无数据则显示"暂无数据"
              if (foundItem) {
                return {
                  orgName: district,
                  tj0602: foundItem.tj0602,
                  tj0603: foundItem.tj0603,
                  tj0604: foundItem.tj0604,
                  tj0605: foundItem.tj0605,
                  // 新增排序用的数值，方便排序
                  sortRank: foundItem.tj0605 ? Number(foundItem.tj0605) : Infinity
                };
              } else {
                return {
                  orgName: district,
                  tj0602: '暂无数据',
                  tj0603: '暂无数据',
                  tj0604: '暂无数据',
                  tj0605: '暂无数据',
                  sortRank: Infinity // 暂无数据的项排序值设为无穷大，放在最后
                };
              }
            }).sort((a, b) => {
              // 按照排序值升序排列（排名1在前，排名2在后...）
              return a.sortRank - b.sortRank;
            });

            // 处理图表数据
            allDistricts.forEach(district => {
              xAxisName.push(district);

              const foundItem = this.tj06List.find(item =>
                  item.orgName && item.orgName.substring(0, 2) === district
              );

              if (foundItem) {
                if (e === 'rate') {
                  xAxisData.push(foundItem.tj0602?Number(foundItem.tj0602.replace('%', '')):0);
                } else {
                  xAxisData.push(foundItem.tj0603?Number(foundItem.tj0603.replace('h', '')):0);
                }
              } else {
                xAxisData.push(null);
              }
            });
            this.countyEffectOption = {
              grid: {
                left: '8%',
                right: '5%',
              },
              xAxis: {
                data: xAxisName,
                axisTick: {
                  show: true
                },
                axisLine: {
                  show: true,
                  lineStyle: {}
                },
                axisLabel: {
                  // rotate: -90,
                }
              },
              yAxis: [{
                type: 'value',
                min: 0,
                splitLine: {
                  show: false,
                  lineStyle: {
                    type: 'dashed',
                    width: 1
                  }
                },
                axisLine: {
                  show: true
                },
                splitArea: {
                  show: false
                }
              }],
              series: {
                data: xAxisData,
                type: 'bar',
                barWidth: '50%',
                label: {
                  show: true,
                  position: 'top',
                  formatter: function(params) {
                    return params.value !== null ? `${params.value}${unit}` : '暂无数据';
                  }
                },
                animationDuration: 2800,
                animationEasing: 'cubicInOut',
              }
            };
          },
            getTableData(parentCode){
                if(parentCode === '330300'){
                    this.columnName = '区划'
                }
                this.tableData = this.initialTableData.filter(item => item.parentCode === parentCode).sort((a, b) => {
                    return b.score - a.score
                })
            },
            rowClick(row){
                const { name, code, parentCode } = row
                if(parentCode === '330300'){
                    this.columnName = name
                    this.getTableData(code)
                }
            }
        }
    }
</script>

<style scoped lang="less">
    ._container {
        padding: 0 10px;
        ._form { margin-bottom: 20px;}
        ._body {
            display: flex; justify-content: space-between; padding-bottom: 20px;
            .item {
                border: 1px solid #dcdfe6; border-radius: 20px; min-height: 500px;
                ._tit {
                    font-size: 20px; text-align: center; padding: 15px 0; position: relative;
                    ::v-deep ._back {
                        position: absolute; z-index: 1; left: 10px;
                    }
                }
                &:nth-child(1){
                    width: 300px;
                    ._chart {
                        width: 100%;
                        height: calc(100% - 70px);
                    }
                }
                &:nth-child(2){
                    margin: 0 20px;
                    width: calc(50% - 40px);
                    ._chart {
                        width: 100%;
                        height: calc(100% - 100px);
                    }
                }
                &:nth-child(3){
                    min-width: 320px;
                    width: calc(50% - 300px); overflow: hidden;
                }
            }
            .tabs {
                display: flex; align-items: center; justify-content: center;
                padding: 0 30px;
                ::v-deep .ant-btn { margin: 0 10px; }
                ::v-deep .ant-btn-primary { color: #fff!important; }
            }
        }
    }
</style>
